package com.jzhao.gper.spring.v3.aop.aspect;

import com.jzhao.gper.spring.v3.aop.intercept.JZJoinPoint;
import lombok.Data;
import org.checkerframework.checker.units.qual.C;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author jzhao
 * @date 2020/4/21 9:09
 */
@Data
public abstract class JZAbstractAspectJAdvice implements JZAdvice{
    private Object aspect;
    private Method adviceMethod;
    private String throwName;

    public JZAbstractAspectJAdvice(Object aspect, Method adviceMethod){
        this.aspect = aspect;
        this.adviceMethod = adviceMethod;
    }

    protected Object invokeAdviceMethod(JZJoinPoint jp, Object returnValue, Throwable ex)
            throws Throwable {
        //执行切面里具体方法
        //获取方法参数类型
        Class<?>[] paramTypes = adviceMethod.getParameterTypes();
        if(null == paramTypes || paramTypes.length == 0){
            return adviceMethod.invoke(aspect);
        } else {
            Object[] args  = new Object[paramTypes.length];
            for (int i = 0; i < paramTypes.length; i++) {
                if(paramTypes[i] == JZJoinPoint.class){
                    args[i] = jp;
                } else if(paramTypes[i] == Throwable.class){
                    args[i] = ex;
                } else{
                    args[i] = returnValue;
                }
            }
            return adviceMethod.invoke(aspect,args);
        }
    }
}
